/*
 * Copyright 2025 arisgo@163.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.arisgo.cloud.flux.configurer.converter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.ResolvableType;
import org.springframework.core.codec.Encoder;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.codec.json.Jackson2JsonEncoder;
import org.springframework.util.MimeType;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * js接收long数据会精度丢失
 * 此方法将返回前端的long转为string
 *
 * @author Arisgo
 * @since 2024/6/13
 */
public class HttpMessageConverterEncoder implements Encoder<Object> {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final Encoder<Object> delegate;
    private final ObjectMapper mapper = new ObjectMapper();

    public HttpMessageConverterEncoder() {
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        mapper.registerModule(simpleModule);

        this.delegate = new Jackson2JsonEncoder(mapper);
    }

    @Override
    public boolean canEncode(ResolvableType elementType, MimeType mimeType) {
        return this.delegate.canEncode(elementType, mimeType);
    }

    @Override
    public List<MimeType> getEncodableMimeTypes() {
        return delegate.getEncodableMimeTypes();
    }

    @Override
    public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory bufferFactory, ResolvableType elementType, MimeType mimeType, Map<String, Object> hints) {
        return Flux.from(inputStream)
                .flatMap(value -> {
                    try {
                        //序列化
                        String res = mapper.writeValueAsString(value);
                        byte[] bytes = res.getBytes(StandardCharsets.UTF_8);
                        DataBuffer dataBuffer = bufferFactory.wrap(bytes);
                        return Mono.just(dataBuffer);
                    } catch (JsonProcessingException e) {
                        logger.error(e.getMessage(), e);
                        return this.delegate.encode(inputStream, bufferFactory, elementType, mimeType, hints);
                    }
                });
    }

}
